package com.example.tools.security.handler;

import cn.hutool.json.JSONUtil;
import com.example.mallcommon.RestResult;
import com.example.mallcommon.constant.ResultCodeEnum;
import com.example.mallcommon.utils.WebUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无效token/token过期 自定义响应
 * @Author: yang
 * @Date: 2021/8/22 0022 14:17
 * @Version 0.0.1
 */
@Component
public class MallAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        String resBody = JSONUtil.toJsonStr(RestResult.custom(ResultCodeEnum.USER_ACCOUNT_UNAUTHENTICATED));
        WebUtils.writeJson(httpServletResponse,resBody);
    }

}
